#include "cv.h"
#include "highgui.h"
#include "CImage.h"
#include <iostream>
#include <fstream>

using namespace std;

CPix::CPix(const char* szFile) // image file
{
    if((m_pImg = cvLoadImage(szFile,0))!=0)
        return;
    else
    {
        cout<<"Error opening image file."<<endl;
        return;
    }

}

CPix::CPix(IplImage* IplSource) //video frame
{
    m_pImg = cvCreateImage(cvGetSize(IplSource),IPL_DEPTH_8U,1);
    cvCvtColor(IplSource, m_pImg, CV_BGR2GRAY); //Gray
}


CPix::~CPix()
{
    //dtor
    cvReleaseImage(&m_pImg);
}

bool CPix::ASC(const char* szFile, scale scDef)
{
    ofstream osTxt(szFile,ios::app);

    char chASC[64] =
    {
        64,35,36,37,38,56,66,77,87,42,
        109,119,113,112,100,98,107,104,97,111,
        81,48,79,90,88,89,85,74,67,76,
        116,102,106,122,120,110,117,118,99,114,
        91,93,123,125,49,40,41,124,47,63,
        73,108,33,105,62,60,43,95,126,45,
        59,44,46,32
    };

	int nH = m_pImg->height/(scDef*2);
	int nW = m_pImg->width/scDef;




    for(int i=0;i<nH;++i)
    {
        for(int j=0;j<nW;++j)
        {
            int gray_index=0;
            for(int k=0;k<(scDef*2);k++)
            {
                for(int h=0;h<scDef;h++)
                {
                    CvScalar csPixel = cvGet2D(m_pImg,i*scDef*2+k,j*scDef+h);
                    gray_index += csPixel.val[0];
                }
            }
            gray_index /= (scDef*scDef*2); //per pixel
            gray_index /= 4;    //scale down to 64-bit
            int n = 0;
            while(n < gray_index && n<64)
				n++;
            osTxt<<chASC[n];
        }
        osTxt<<endl;
    }
    osTxt<<"\t"<<endl;
    osTxt.close();
    return true;


}
